package com.kernel.streamDemo;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/****************************************
 * @name ZipOutputStreamDemo
 * @description 压缩文件或文件夹
 * @author 黄彬恒
 * @since 2018/8/21
 ***************************************/
public class ZipOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\ideaProgram\\IOLearning\\src\\main\\resources\\testDir\\test2");
        File zipFile = new File("D:\\ideaProgram\\IOLearning\\src\\main\\resources\\testDir\\test22.zip");
        InputStream input;
        ZipOutputStream zipOut;// 声明压缩流对象
        zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
        zipOut.setComment("https://gitee.com/helicopter/IOLearning");
        int temp;
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles != null) {
                for (File listFile : listFiles) {
                    input = new FileInputStream(listFile);
                    zipOut.putNextEntry(new ZipEntry(file.getName() + File.separator + listFile.getName()));
                    while ((temp = input.read()) != -1) {// 边读边写
                        zipOut.write(temp);
                    }
                    input.close();
                }
            }
        } else {
            input = new FileInputStream(file);
            zipOut.putNextEntry(new ZipEntry(file.getName()));
            while ((temp = input.read()) != -1) {// 边读边写
                zipOut.write(temp);
            }
            input.close();
        }
        zipOut.close();
    }
}
